import React, { useState } from 'react';
import { StyleSheet, View, TouchableOpacity, Alert, KeyboardAvoidingView, Platform, ScrollView } from 'react-native';
import { TextInput, Button } from 'react-native-paper';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';

import { ThemedText } from '@/components/ThemedText';
import { ThemedView } from '@/components/ThemedView';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
import { useAuth } from '@/contexts/AuthContext';

export default function ChangePasswordScreen() {
  const colorScheme = useColorScheme();
  const tintColor = Colors[colorScheme ?? 'light'].tint;
  const router = useRouter();
  const { changePassword } = useAuth();
  
  // 表单状态
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  
  // 密码可见性状态
  const [currentPasswordVisible, setCurrentPasswordVisible] = useState(false);
  const [newPasswordVisible, setNewPasswordVisible] = useState(false);
  const [confirmPasswordVisible, setConfirmPasswordVisible] = useState(false);
  
  // 验证密码强度
  const validatePassword = (password: string) => {
    // 密码至少8位，包含字母和数字
    const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
    return passwordRegex.test(password);
  };
  
  // 提交修改密码
  const handleSubmit = async () => {
    // 表单验证
    if (!currentPassword || !newPassword || !confirmPassword) {
      Alert.alert('错误', '请填写所有密码字段');
      return;
    }
    
    // 验证新密码强度
    if (!validatePassword(newPassword)) {
      Alert.alert('错误', '新密码至少需要8位，且包含字母和数字');
      return;
    }
    
    // 验证两次输入的新密码是否一致
    if (newPassword !== confirmPassword) {
      Alert.alert('错误', '两次输入的新密码不一致');
      return;
    }
    
    // 验证新密码不能与当前密码相同
    if (newPassword === currentPassword) {
      Alert.alert('错误', '新密码不能与当前密码相同');
      return;
    }
    
    setIsLoading(true);
    try {
      const success = await changePassword(currentPassword, newPassword);
      
      if (success) {
        Alert.alert('成功', '密码已成功修改', [
          { text: '确定', onPress: () => router.back() }
        ]);
      } else {
        Alert.alert('错误', '当前密码不正确或修改密码失败');
      }
    } catch (error) {
      Alert.alert('错误', '发生未知错误，请重试');
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };
  
  return (
    <ThemedView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
          <MaterialCommunityIcons name="arrow-left" size={28} color={tintColor} />
        </TouchableOpacity>
        <ThemedText style={styles.headerTitle}>修改密码</ThemedText>
        <View style={styles.placeholder} />
      </View>
      
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardAvoidingView}
      >
        <ScrollView style={styles.scrollView}>
          <View style={styles.formContainer}>
            <ThemedText style={styles.formDescription}>
              为了保护您的账户安全，请输入当前密码和新密码。新密码必须至少包含8个字符，并且包含字母和数字。
            </ThemedText>
            
            <TextInput
              label="当前密码"
              value={currentPassword}
              onChangeText={setCurrentPassword}
              mode="outlined"
              style={styles.input}
              secureTextEntry={!currentPasswordVisible}
              left={<TextInput.Icon icon="lock" color={tintColor} />}
              right={
                <TextInput.Icon
                  icon={currentPasswordVisible ? "eye-off" : "eye"}
                  color="#888"
                  onPress={() => setCurrentPasswordVisible(!currentPasswordVisible)}
                />
              }
              outlineColor="#CCCCCC"
              activeOutlineColor={tintColor}
              theme={{ roundness: 10 }}
            />
            
            <TextInput
              label="新密码"
              value={newPassword}
              onChangeText={setNewPassword}
              mode="outlined"
              style={styles.input}
              secureTextEntry={!newPasswordVisible}
              left={<TextInput.Icon icon="lock-reset" color={tintColor} />}
              right={
                <TextInput.Icon
                  icon={newPasswordVisible ? "eye-off" : "eye"}
                  color="#888"
                  onPress={() => setNewPasswordVisible(!newPasswordVisible)}
                />
              }
              outlineColor="#CCCCCC"
              activeOutlineColor={tintColor}
              theme={{ roundness: 10 }}
            />
            
            <TextInput
              label="确认新密码"
              value={confirmPassword}
              onChangeText={setConfirmPassword}
              mode="outlined"
              style={styles.input}
              secureTextEntry={!confirmPasswordVisible}
              left={<TextInput.Icon icon="lock-check" color={tintColor} />}
              right={
                <TextInput.Icon
                  icon={confirmPasswordVisible ? "eye-off" : "eye"}
                  color="#888"
                  onPress={() => setConfirmPasswordVisible(!confirmPasswordVisible)}
                />
              }
              outlineColor="#CCCCCC"
              activeOutlineColor={tintColor}
              theme={{ roundness: 10 }}
            />
            
            <Button
              mode="contained"
              onPress={handleSubmit}
              style={styles.submitButton}
              loading={isLoading}
              disabled={isLoading}
              buttonColor={tintColor}
            >
              确认修改
            </Button>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingTop: 60,
    paddingBottom: 15,
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#E1E1E1',
  },
  backButton: {
    width: 40,
    height: 40,
    justifyContent: 'center',
    alignItems: 'flex-start',
  },
  headerTitle: {
    fontSize: 22,
    fontWeight: 'bold',
  },
  placeholder: {
    width: 40,
  },
  keyboardAvoidingView: {
    flex: 1,
  },
  scrollView: {
    flex: 1,
  },
  formContainer: {
    padding: 20,
  },
  formDescription: {
    fontSize: 16,
    marginBottom: 20,
    lineHeight: 22,
  },
  input: {
    marginBottom: 16,
    backgroundColor: 'transparent',
  },
  submitButton: {
    marginTop: 20,
    paddingVertical: 8,
    borderRadius: 10,
  },
});